package com.caibq.controller;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * projectName: demoBox
 *
 * @author: caicai
 * time: 2024/1/3 15:23 周三
 * description:异步编排
 */
public class CompletableFutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //异步发起第一个任务
        CompletableFuture<String> firstTask = CompletableFuture.supplyAsync(() -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return "第一个任务的结果";
                }
        );
        //异步发起第二个任务
        CompletableFuture<String> secondTask = CompletableFuture.supplyAsync(() -> "第二个任务的结果");

        // 合并两个任务的结果
        CompletableFuture<String> combineTask = firstTask.thenCombineAsync(secondTask, (firstResult, secondResult) -> {
            return firstResult + "&&" + secondResult;
        });

        combineTask.thenAccept((result) -> {
            System.out.println("最终结果：" + result);
        });


        System.out.println("其他任务，该干嘛干嘛");

        combineTask.join();
    }
}

